<?php
declare (strict_types=1);

namespace app\sysuser\controller\subject;

use app\common\controller\SysBackend;
use app\common\enums\SubjectKnowledgeStatusEnum;
use app\common\model\banxi\subject\Subject as SubjectModel;
use app\common\model\banxi\subject\SubjectGrade as SubjectGradeModel;
use app\common\model\banxi\subject\SubjectKnowledge as SubjectKnowledgeModel;
use think\db\exception\DbException;
use think\exception\ValidateException;
use think\facade\Validate;
use think\validate\ValidateRule;

class Knowledge extends SysBackend
{
    protected array $noNeedLogin = [];
    protected array $noNeedPermission = [];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new SubjectKnowledgeModel();
    }


    /**
     * 分页查询
     * @return void
     * @throws DbException
     */
    public function listPage(): void
    {
        $param = $this->request->param(['index', 'limit', 'orderBy', "query", 'knowledgeId' => 0]);
        $knowledgeId = $param['knowledgeId'];
        if (!empty($param['knowledgeId'])) {
            $isExists = $this->model->where('id', $knowledgeId)->count() > 0;
            if (!$isExists) {
                $this->fail('知识点不存在');
            }
        }
        $param['query']['EQ_pid'] = $knowledgeId;

        //查询条件解析
        $where = get_query($param);
        //获取分页数据
        $pageParams = get_page_params($param);
        $list = $this->model->where($where)
            ->with([
                'subject' => function ($query) {
                    $query->field('id,name');
                }, 'subjectGrade' => function ($query) {
                    $query->field('id,name');
                }])
            ->order(['id' => 'asc', 'sortNum' => 'desc'])
            ->paginate([
                'page' => $pageParams['page'],
                'list_rows' => $pageParams['limit'],
            ]);
        $this->ok('操作成功', result_row($list));
    }

    /**
     * 分页Select查询
     * @return void
     * @throws DbException
     */
    public function listSelectPage(): void
    {
        $param = $this->request->param(['index', 'limit', 'orderBy', "query", 'knowledgeId' => 0]);
        $knowledgeId = $param['knowledgeId'];
        if (!empty($param['knowledgeId'])) {
            $isExists = $this->model->where('id', $knowledgeId)->count() > 0;
            if (!$isExists) {
                $this->fail('知识点不存在');
            }
        }
        $param['query']['EQ_pid'] = $knowledgeId;
        //查询条件解析
        $where = get_query($param);
        //获取分页数据
        $pageParams = get_page_params($param);
        $list = $this->model->where($where)
            ->field('id,name')
            ->order(['id' => 'asc', 'sortNum' => 'desc'])
            ->paginate([
                'page' => $pageParams['page'],
                'list_rows' => $pageParams['limit'],
            ]);
        $this->ok('操作成功', result_row($list));
    }

    public function listTreePage()
    {
        $param = $this->request->param(['query' => [], 'knowledgeId' => 0]);
        $param['query']['EQ_status'] = SubjectKnowledgeStatusEnum::E1;
        $where = get_query($param);
        $whereOr = [];
        if ($param['knowledgeId']) {
            $knowledgeInfo = $this->model->where('id', $param['knowledgeId'])->find();
            if (!$knowledgeInfo) {
                $this->fail('知识点不存在');
            }
            if ($knowledgeInfo['pid'] > 0) {
                $knowledgeInfo = $this->model->where('id', $knowledgeInfo['pid'])->find();
                if (!$knowledgeInfo) {
                    $this->fail('知识点不存在');
                }
            }
            $whereOr = [
                ['id', '=', $knowledgeInfo['id']],
                ['pid', '=', $knowledgeInfo['id']],
            ];
        }

        $list = $this->model
            ->where($where)
            ->whereOr($whereOr)
            ->field('id as value,name as label,pid')
            ->order(['id' => 'asc', 'sortNum' => 'desc'])
            ->select();
        $list = secondaryTreeSelect($list, 'value', 'pid');
        $this->ok('操作成功', $list);
    }

    /**
     * 查询
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get()
    {
        $param = $this->request->param(["query" => []]);
        if (empty($param['query'])) {
            $this->fail('请传递你要查询的记录');
        }
        $where = get_query($param);
        $info = $this->model->where($where)->find();
        if (empty($info)) {
            $this->fail('记录不存在');
        }
        $this->ok('操作成功', $info);
    }

    /**
     * 新增或修改
     * @return void
     */
    public function saveOrUpdate()
    {
        $param = $this->request->filter('')->param([
            'id' => null,
            'pid' => 0,
            'name' => '',
            'content' => '',
            'subjectId' => 0,
            'subjectGradeId' => 0,
            'sortNum' => 0,
            'status' => 0,
        ]);
        try {
            $validate = Validate::rule([
                "pid" => function ($value) {
                    if ($value == 0) return true;
                    $isExists = $this->model->where(['pid' => 0, 'id' => $value])->count() > 0;
                    if (!$isExists) {
                        return '设置的上级知识点不存在或不是一级知识点';
                    }
                    return true;
                },
                'name' => function ($value, $data) {
                    if (empty($value)) {
                        return '请输入知识点名称';
                    }
                    $where = [['name', '=', $value]];
                    if (!empty($data['id'])) {
                        $where[] = ['id', '<>', $data['id']];
                    }
                    $isExists = $this->model->where($where)->count() > 0;
                    if ($isExists) {
                        return '知识点名称已存在';
                    }
                    return true;
                },
                'content' => ValidateRule::isRequire(null, '请输入知识点讲解'),
                'subjectId' => function ($value,$data) {
                    if ($data['pid'] > 0) {
                        return true;
                    }
                    if (empty($value)) {
                        return '请选择科目';
                    }
                    $isExists = SubjectModel::where('id', $value)->count() > 0;
                    if (!$isExists) {
                        return '科目不存在';
                    }
                    return true;
                },
                'subjectGradeId' => function ($value,$data)  {
                    if ($data['pid'] > 0) {
                        return true;
                    }
                    if (empty($value)) {
                        return '请选择年级';
                    }
                    $isExists = SubjectGradeModel::where('id', $value)->count() > 0;
                    if (!$isExists) {
                        return '年级不存在';
                    }
                    return true;
                },
                'sortNum' => ValidateRule::isNumber(null, '请输入正确的排序数字'),
                'status' => ValidateRule::in([1, 2], '请输入正确的状态')
            ]);
            if (!$validate->check($param)) throw new ValidateException($validate->getError());
            $this->model->saveOrUpdate($param);
        } catch (ValidateException $exception) {
            $this->fail($exception->getMessage());
        }
        $this->ok('操作成功', [], self::NOTIFICATION);
    }


    /**
     * 删除
     * @return void
     */
    public function del()
    {
        $param = $this->request->param(['ids' => []]);
        try {
            $validate = Validate::rule([
                'ids' => ValidateRule::isRequire(null, '请选择你要删除的记录'),
            ]);
            if (!$validate->check($param)) throw new ValidateException($validate->getError());
            SubjectKnowledgeModel::destroy(function ($query) use ($param) {
                $query->whereIn('id', $param['ids']);
            });
        } catch (ValidateException $exception) {
            $this->fail($exception->getMessage());
        }
        $this->ok('操作成功', [], self::NOTIFICATION);
    }
}
